import { deleteWorkOrder, fetchWorkOrderList, createWorkOrder, updateWorkOrder, detailWorkOrder, replyWorkOrder } from '@/services/ant-design-pro/work-order';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { FooterToolbar, PageContainer, ProTable, ProForm, ProFormText, ProFormSelect, ProFormTextArea, ProFormGroup } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { Button, Drawer, message, Popconfirm, Modal, Image, Form, Descriptions } from 'antd';
import React, { act, useCallback, useRef, useState } from 'react';
import ImageUploadMajority from '@/components/ImageUploadMajority';
import TextArea from 'antd/es/input/TextArea';

const WorkOrderList: React.FC = () => {
  const [images, setImages] = useState([]);
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<API.WorkOrderItem | undefined>();
  const [isEditMode, setIsEditMode] = useState<boolean>(false); // 判断是编辑还是新增
  const [selectedRowsState, setSelectedRows] = useState<API.WorkOrderItem[]>([]);
  const [form] = ProForm.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [replyModalVisible, setReplyModalVisible] = useState<boolean>(false);
  const [replyContent, setReplyContent] = useState<string>('');
  const [activeKey, setActiveKey] = useState<string>('');

  const { run: delRun, loading: deleteLoading } = useRequest(deleteWorkOrder, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('删除成功');
    },
    onError: () => {
      messageApi.error('删除错误');
    },
  });

  const { run: detailRun } = useRequest(detailWorkOrder, {
    manual: true,
    onSuccess: (data) => {
      form.setFieldsValue(data);
      setCurrentRow(data);
      setDrawerVisible(true);
    },
    onError: () => {
      messageApi.error('获取详情错误');
    },
  });

  const handleSave = useCallback(
    async (values: API.WorkOrderItem) => {
      if (isEditMode) {
        await updateWorkOrder({ ...currentRow, ...values });
        messageApi.success('更新成功');
      } else {
        await createWorkOrder(values);
        messageApi.success('添加成功');
      }
      setDrawerVisible(false);
      actionRef.current?.reload();
    },
    [isEditMode, currentRow, actionRef],
  );

  const columns: ProColumns<API.WorkOrderItem>[] = [
    {
      title: '工单名称',
      dataIndex: 'workName',
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => {
          setIsEditMode(true);
          detailRun({ id: record.id });
        }}>{text}</a>
      )
    },
    {
      title: '工单类型',
      dataIndex: 'workType',
      valueEnum: {
        1: { text: '数据产品' },
        2: { text: '类型2' },
      },
    },
   
    {
      title: '用户名称',
      dataIndex: 'userName',
      ellipsis: true
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
    },
    {
      title: '工单状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: { text: '未处理' },
        1: { text: '处理中' },
        2: { text: '已完结' },
      },
      
      search: false,
    },
    {
      title: '问题描述',
      dataIndex: 'workContent',
      search: false,
      width: 200,
      ellipsis: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      width: 120,
      ellipsis: true,
      search: false
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      align: 'center',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setIsEditMode(true);
            detailRun({ id: record.id });
          }}
        >
          查看
        </a>,
        <Popconfirm
          key="delete"
          title="确定删除该工单吗？"
          onConfirm={() => handleRemove([record])}
        >
          <a>删除</a>
        </Popconfirm>,
        <a
          key="reply"
          onClick={() => {
            setCurrentRow(record);
            setReplyModalVisible(true);
          }}
        >
          回复
        </a>,
      ],
    },
  ];

  const handleRemove = useCallback(
    async (selectedRows: API.WorkOrderItem[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');
        return;
      }
      await delRun({
        params: {
          id: selectedRows.map((row) => row.id).join(','),
        },
      });
    },
    [delRun],
  );

  const handleReply = useCallback(
    async () => {
      if (!currentRow) {
        messageApi.warning('请选择要回复的工单');
        return;
      }
      // 假设你有一个回复工单的 API 方法
      console.log(currentRow, '回复')
      await replyWorkOrder({ ...currentRow, replyContent, picture: images.join(',') });
      messageApi.success('回复成功');
      setReplyModalVisible(false);
      setImages([])
      setReplyContent('')
      detailRun({ id: currentRow.id });
      actionRef.current?.reload();

    },
    [currentRow, replyContent, actionRef],
  );

  return (
    <PageContainer header={{ title: '' }}>
      {contextHolder}
      <ProTable<API.WorkOrderItem, API.PageParams>
        headerTitle="工单列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        toolBarRender={() => [
          // <Button
          //   key={'button'}
          //   type="primary"
          //   onClick={() => {
          //     setCurrentRow(undefined);
          //     setIsEditMode(false);
          //     form.resetFields();
          //     setDrawerVisible(true);
          //   }}
          // >
          //   新建工单
          // </Button>,
        ]}

        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: "", label: <span>全部</span> },
              { key: "0", label: <span>未处理</span> },
              { key: "1", label: <span>处理中</span> },
              { key: "2", label: <span>已完结</span> },
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
        request={ (params) => fetchWorkOrderList({...params, status: activeKey})}
        columns={columns}
      // rowSelection={{
      //   onChange: (_, selectedRows) => {
      //     setSelectedRows(selectedRows);
      //   },
      // }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选中 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            loading={deleteLoading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        z-index={1}
        title={isEditMode ? '查看工单' : '新建工单'}
        width={1000}
        open={drawerVisible}
        footer={<Button type='primary' onClick={() => { setReplyModalVisible(true); console.log(123) }}> 回复 </Button>}
        onClose={() => {
          setDrawerVisible(false);
        }}
        closable={false}
      >
        <Descriptions bordered title="工单信息"  style={{ marginTop: 24 }}  column={2}>
        <Descriptions.Item label="工单名称">{currentRow?.workName || '-'}</Descriptions.Item>
          <Descriptions.Item label="描述">
            {<div>{currentRow?.workContent}</div>}
            {  form.getFieldValue('file')?.split(',').map((item, index) => (
              <Image key={index} width={50} src={item} />
            ))}
          </Descriptions.Item>
         
          <Descriptions.Item label="工单类型">{currentRow?.workType === '1' ? '数据产品' : '类型2'}</Descriptions.Item>
          <Descriptions.Item label="提交用户">{currentRow?.userName || '-'}</Descriptions.Item>
          <Descriptions.Item label="手机号">{currentRow?.mobile || '-'}</Descriptions.Item>
          {/* <Descriptions.Item label="工单内容">{currentRow?.workContent || '-'}</Descriptions.Item> */}
          <Descriptions.Item label="工单状态">{currentRow?.status === 0 ? '未处理' : currentRow?.status === 1 ? '处理中' : '已完结'}</Descriptions.Item>
          <Descriptions.Item label="提交时间">{currentRow?.createTime || '-'}</Descriptions.Item>
        </Descriptions>

        <Descriptions bordered column={1} title="内容回复"  style={{ marginTop: 24 }} >
          {isEditMode && currentRow?.workOrderDetails && (
            <>
              {currentRow.workOrderDetails.map((detail) => (
                <Descriptions.Item key={detail.id} label={`${detail.userName} `}>
                  <div dangerouslySetInnerHTML={{ __html:`<p> ${detail.createTime} :</p>`+ detail.replyContent }} />
                  <div>
                    {detail.picture && detail.picture.split(',').map((item, index) => (
                      <Image key={index} width={50} src={item} style={{ padding: '5px' }} />
                    ))}
                  </div>
                </Descriptions.Item>
              ))}
            </>
          )}
        </Descriptions>

      </Drawer>
      <Modal
        title="回复工单"
        open={replyModalVisible}
        onCancel={() => setReplyModalVisible(false)}
        onOk={handleReply}
        zIndex={999999}
      >
        <div>
          <ImageUploadMajority value={images} onChange={setImages} />
        </div>
        <TextArea
          value={replyContent}
          onChange={(e) => setReplyContent(e.target.value)}
          autoSize={{ minRows: 5, maxRows: 8 }}
        />
      </Modal>


    </PageContainer>
  );
};

export default WorkOrderList;